#include "GameManager.h"
#include "EventManager.h"
// opens the window and exports classes to lua
GameManager::GameManager(unsigned int width, unsigned int height, std::string title)
:   _window(width, height, title),
    _alive(false)
{
    _eventMgr = EventManager::instance();
    ScriptManager::instance()->exportToLua();
}

// deletes the allocated data for each state
GameManager::~GameManager()
{
    for(unsigned int i; i < _states.size(); i++)
    {
        if(_states[i])
            delete _states[i];
    }
    _states.clear();
}

void GameManager::init()
{
}

// runs the main game loop
void GameManager::run()
{
    while(_window.open())
    {
        update();
        handleEvents();
        render();
    }
}


// renders the screen and whatever the current state is rendering
void GameManager::render()
{
    _window.clear();
    if(_alive)
        _states.back()->render();
    _window.display();
}

// updates the current state
void GameManager::update()
{
    if(_alive)
        _states.back()->update();
}


// handles the window and current event's states
void GameManager::handleEvents()
{
    if(_alive)
        _states.back()->handleEvents(_event);
}

// adds a new state to the stack, sets that state to the active state
void GameManager::pushState(State* s)
{
    s->init();
    _states.push_back(s);
    _alive = true;
}
/*
* pops a state off the stack, the most previously state pushed
* before the current state is now the active state. if there are
* no states left it sets the _alive var to false so the program
* dosent try to access data thats not there
*/
void GameManager::popState()
{
    if(_states.size() > 0)
    {
        if(_states.back())
            delete _states.back();
        _states.pop_back();
    }
    else
    {
        _alive = false;
    }
}


